#!/usr/bin/env python
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#  * Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#  * Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#  * Neither the name of NVIDIA CORPORATION nor the names of its
#    contributors may be used to endorse or promote products derived
#    from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import argparse
import numpy as np
import os
from builtins import range
#from tensorrtserver.api import *
import cv2
#import tritongrpcclient
import tritonclient.http as httpclient
from tritonclient.utils import InferenceServerException


def cos_sim(feature_1,feature_2):
    return np.dot(feature_1,feature_2)/(np.linalg.norm(feature_1)*np.linalg.norm(feature_2))

def findCosineDistance(vector1, vector2):
    vec1 = vector1.flatten()
    vec2 = vector2.flatten()
    a = abs(np.dot(vec1.T, vec2))
    b = np.dot(vec1.T, vec1)
    c = np.dot(vec2.T, vec2)
    return 1 - (a/(np.sqrt(b)*np.sqrt(c)))


def get_feature(triton_client,image_url):
    model_name = "arcface-100"
    model_version = 1
    batch_size = 1
    #infer_ctx = InferContext('localhost:28001', protocol, model_name, model_version,http_headers=None, verbose=False)
    img = cv2.imread(image_url)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img_data = np.array(img)
    img_data = np.subtract(img_data,127.5)
    img_data = np.true_divide(img_data,128)
    img_data = np.transpose(img_data, [2, 0, 1])
    img_data = np.expand_dims(img_data, 0).astype('float32')
    inputs =[]
    inputs.append(httpclient.InferInput('data', [1, 3, 112, 112], "FP32"))
    outputs = []
    inputs[0].set_data_from_numpy(img_data)

    '''
    result = infer_ctx.run({ 'data' : (img_data,) },
                           { 'fc1' : InferContext.ResultFormat.RAW},
                           batch_size)
    '''
    #outputs.append(tritongrpcclient.InferRequestedOutput("prob"))
    outputs.append(httpclient.InferRequestedOutput('prob'))
    async_request = triton_client.async_infer(
        model_name=model_name, inputs=inputs,  outputs=outputs, headers={"test": "1"}
    )
    results = async_request.get_result()
   # print(type(result["fc1"][0]))
    #print(result["fc1"][0].shape)

    feature = np.frombuffer(results.as_numpy("prob"), dtype=np.float32)
    #feature = preprocessing.normalize(result['prob'][0].reshape(1,-1)).flatten()
    #feature = result['prob'][0]
    return feature
if __name__ == '__main__':
    try:
        triton_client = httpclient.InferenceServerClient(
                url="192.168.0.147:18000", verbose=False)
    except Exception as e:
        print("channel creation failed: " + str(e))
        sys.exit()
    feature_1 = get_feature(triton_client,"huangzhe_330.jpg")
    feature_2 = get_feature(triton_client,"huangzhe_345.jpg")
    feature_3 = get_feature(triton_client,"liximeng_143.jpg")
    feature_4 = get_feature(triton_client,"liximeng_128.jpg")
    #print(feature_1.shape)

    #cos_sim=np.dot(feature_1,feature_2)/(np.linalg.norm(feature_1)*np.linalg.norm(feature_2))
    print(cos_sim(feature_1,feature_2))
    print(cos_sim(feature_2,feature_3))
    print(cos_sim(feature_1,feature_3))
    print(cos_sim(feature_1,feature_4))
    print(cos_sim(feature_3,feature_4))
    #print(feature_3[-1])
